package com.infore.airsupervise.ui.activity;

import android.content.Intent;
import android.os.Bundle;
import android.os.Parcelable;
import android.support.v7.widget.LinearLayoutManager;
import android.support.v7.widget.RecyclerView;
import android.view.View;
import android.widget.CompoundButton;
import android.widget.EditText;
import android.widget.LinearLayout;
import android.widget.TableLayout;

import com.beardedhen.androidbootstrap.AwesomeTextView;
import com.beardedhen.androidbootstrap.BootstrapButton;
import com.beardedhen.androidbootstrap.font.FontAwesome;
import com.infore.airsupervise.R;
import com.infore.airsupervise.adapter.SiteModelAdapter;
import com.infore.airsupervise.app.Constants;
import com.infore.airsupervise.bean.LawingSiteE;
import com.infore.airsupervise.bean.PolluterE;
import com.infore.airsupervise.other.listener.DateAndTimeBiz;
import com.infore.airsupervise.other.listener.DateAndTimeBizImpl;
import com.infore.airsupervise.other.listener.DateAndTimeListener;
import com.infore.airsupervise.other.listener.LayoutControl;
import com.infore.airsupervise.other.listener.LayoutControlListener;
import com.infore.airsupervise.ui.fragment.PsonSelectorFragment;
import com.infore.airsupervise.utils.JumpUtil;
import com.infore.airsupervise.utils.ToastUtil;
import com.rey.material.widget.RadioButton;

import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.ButterKnife;
import butterknife.OnClick;

/**
 * 创建现场检查（勘查）笔录
 */
public class SiteInspectCreateActivity extends BaseTitleBarActivity {

    @BindView(R.id.tv_info_arrow)
    AwesomeTextView tvInfoArrow;

    @BindView(R.id.et_address)
    EditText etAddress;
    @BindView(R.id.et_unit)
    EditText etUnit;
    @BindView(R.id.et_leader_name)
    EditText etLeaderName;
    @BindView(R.id.et_leader_age)
    EditText etLeaderAge;
    @BindView(R.id.et_identify)
    EditText etIdentify;
    @BindView(R.id.et_source)
    EditText etSource;
    @BindView(R.id.et_position)
    EditText etPosition;
    @BindView(R.id.et_phone)
    EditText etPhone;
    @BindView(R.id.et_relationship)
    EditText etRelationship;
    @BindView(R.id.et_address_inspect)
    EditText etAddressInspect;
    @BindView(R.id.et_postCode)
    EditText etPostCode;
    @BindView(R.id.et_other)
    EditText etOther;
    @BindView(R.id.rb_evite_false)
    RadioButton rbEviteFalse;
    @BindView(R.id.rb_evite_true)
    RadioButton rbEviteTrue;
    @BindView(R.id.tv_condition_arrow)
    AwesomeTextView tvConditionArrow;
    @BindView(R.id.ll_condition)
    LinearLayout llCondition;
    @BindView(R.id.rv_askModel)
    RecyclerView rvAskModel;
    @BindView(R.id.tv_askModel_add)
    BootstrapButton tvAskModelAdd;
    @BindView(R.id.tv_askModel_sentence)
    BootstrapButton tvSentence;
    @BindView(R.id.tl_info)
    TableLayout tlInfo;
    @BindView(R.id.et_startTime)
    EditText etStartTime;
    @BindView(R.id.et_endTime)
    EditText etEndTime;

    private LayoutControlListener layoutControl;
    private LawingSiteE.NotesJC inspectE;//检查记录
    private PsonSelectorFragment inspectFra; //检查人
    private PsonSelectorFragment noteFra;// 记录人
    private PolluterE polluterE ; // 污染源

    private  int position ; //检查记录对应的索引
    private DateAndTimeBiz dateAndTimeBiz; //时间选择的实现类

    private SiteModelAdapter adapter ; //勘察情况列表适配器
    private List<LawingSiteE.NoteModel> noteModelList = new ArrayList<>(); //勘察情况

    @Override
    protected void onCreate(Bundle savedInstanceState) {
        super.onCreate(savedInstanceState);
        setContentView(R.layout.activity_site_inspect_create);
        ButterKnife.bind(this);
        Intent it = getIntent();
        if(null != it ){
            position = it.getIntExtra(Constants.INTENT_INT_KEY,-1);
            inspectE = (LawingSiteE.NotesJC) it.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            polluterE = (PolluterE) it.getSerializableExtra("intent_polluter");
        }
        title.setText("创建现场检查（勘查）笔录");
        rightMenu.setFontAwesomeIcon(FontAwesome.FA_CHECK);
        layoutControl = new LayoutControl(ctx);
        initView();
        if(null != inspectE){
            setInspectEData();
        }else {
            inspectE = new LawingSiteE.NotesJC();
            //添加当前用户为默认的检查人 记录人
            inspectFra.addDefaultPson();
            noteFra.addDefaultPson();
        }
        setPolluterData();

    }

    private void initView() {
        //人员选择
        inspectFra = new PsonSelectorFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_inspect_pson, inspectFra, null).commit();
        noteFra = new PsonSelectorFragment();
        getSupportFragmentManager().beginTransaction()
                .replace(R.id.fl_note_pson, noteFra, null).commit();
        //是否申请回避
        rbEviteFalse.setOnCheckedChangeListener(checkListner);
        rbEviteTrue.setOnCheckedChangeListener(checkListner);
        //
        dateAndTimeBiz = new DateAndTimeBizImpl();
        //recyclerview
        rvAskModel.setLayoutManager( new LinearLayoutManager(ctx));
        adapter = new SiteModelAdapter(R.layout.item_site_inspectmodel,noteModelList);
        rvAskModel.setAdapter(adapter);
    }

    private void initInspectData() {
        inspectE.setStartTime(etStartTime.getText().toString());//时间
        inspectE.setEndTime(etEndTime.getText().toString());
        inspectE.setAddress(etAddress.getText().toString());

        inspectE.setUnit(etUnit.getText().toString());//单位
        inspectE.setLeaderName(etLeaderName.getText().toString()); //现场负责人
        inspectE.setLeaderAge(etLeaderAge.getText().toString());//年龄
        inspectE.setIdentify(etIdentify.getText().toString());//身份证
        inspectE.setCompany(etSource.getText().toString());//被检查单位
        inspectE.setPosition(etPosition.getText().toString());//职位
        inspectE.setRelationship(etRelationship.getText().toString());//与本案关系
        inspectE.setAddressInspect(etAddressInspect.getText().toString());//检查地点
        inspectE.setPostCode(etPostCode.getText().toString());//邮编
        inspectE.setPhone(etPhone.getText().toString());//电话
        inspectE.setOthers(etOther.getText().toString());
        inspectE.setNoteModels(noteModelList);
        inspectE.setEvite(rbEviteTrue.isChecked() ? 0: 1); //是否申请回避b
        inspectE.setInspectPson(inspectFra.getAllPsonList()); //检查人员
        inspectE.setNotePson(noteFra.getAllPsonList());
    }

    /**
     * 再编辑
     */
    private void setInspectEData(){
        etAddress.setText(inspectE.getAddress());
        etIdentify.setText(inspectE.getIdentify());
        etLeaderAge.setText(inspectE.getLeaderAge());
        etRelationship.setText(inspectE.getRelationship());
        etPostCode.setText(inspectE.getPostCode());
        etUnit.setText(inspectE.getUnit());
        etPhone.setText(inspectE.getPhone());
        etOther.setText(inspectE.getOthers());
        etPosition.setText(inspectE.getPosition());
        etLeaderName.setText(inspectE.getLeaderName());
        etStartTime.setText(inspectE.getStartTime());
        etEndTime.setText(inspectE.getEndTime());
        noteModelList.addAll(inspectE.getNoteModels());
        if(inspectE.getEvite() == 0){
            rbEviteTrue.setChecked(true);
        }else {
            rbEviteFalse.setChecked(true);
        }
        inspectFra.addPsonList(inspectE.getInspectPson());
        noteFra.addPsonList(inspectE.getNotePson());
    }

    /**
     * 污染源信息
     */
    private void setPolluterData(){
        if(null != polluterE) {
            etSource.setText(polluterE.getName());
            etAddressInspect.setText(polluterE.getAddress());
        }
    }

    private boolean isInfoShowed;
    private boolean isConditionShowed;

    @OnClick({R.id.ll_info_control, R.id.ll_condition_control,R.id.et_endTime,
            R.id.et_startTime,R.id.tv_askModel_sentence,R.id.tv_askModel_add ,
    R.id.et_source})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.ll_info_control:
                isInfoShowed = !isInfoShowed;
                layoutControl.layoutControl(isInfoShowed, tlInfo, tvInfoArrow);
                break;
            case R.id.ll_condition_control:
                isConditionShowed = !isConditionShowed;
                layoutControl.layoutControl(isConditionShowed, llCondition, tvInfoArrow);
                break;
            case R.id.et_startTime:
                dateAndTimeBiz.getDateAndTimePicker(getSupportFragmentManager(), new DateAndTimeListener() {
                    @Override
                    public void getDateAndTimeString(String dateAndTime) {
                        etStartTime.setText(dateAndTime);
                    }
                });
                break;
            case R.id.et_endTime:
                dateAndTimeBiz.getDateAndTimePicker(getSupportFragmentManager(), new DateAndTimeListener() {
                    @Override
                    public void getDateAndTimeString(String dateAndTime) {
                        etEndTime.setText(dateAndTime);
                    }
                });
                break;
            case R.id.tv_askModel_add : //添加模块
                adapter.addData( new LawingSiteE.NoteModel());
                break;
            case R.id.tv_askModel_sentence : //选择模板语句
                ToastUtil.showShort(ctx,"请手动填写");
                break;
            case R.id.et_source : //选择污染源
                ToastUtil.showShort(ctx, "选择一个污染源");
                JumpUtil.ForResultJumpFromTo(this, PolluterSearchActivity.class, 99, Constants.INTENT_INT_KEY, 1);
                break;
        }
    }

    /**
     * 单选组
     */
    private CompoundButton.OnCheckedChangeListener checkListner = new CompoundButton.OnCheckedChangeListener() {
        @Override
        public void onCheckedChanged(CompoundButton compoundButton, boolean b) {
            if (b) {
                rbEviteTrue.setChecked(compoundButton == rbEviteTrue);
                rbEviteFalse.setChecked(compoundButton == rbEviteFalse);
            }
        }
    };

    @Override
    protected void onRightMenuClick(View view) {
        super.onRightMenuClick(view);
        initInspectData();
        Intent it = new Intent();
        it.putExtra(Constants.INTENT_OBJ_KEY,  inspectE);
        it.putExtra(Constants.INTENT_INT_KEY,position);
        it.putExtra("intent_polluter",polluterE);
        setResult(RESULT_OK,it);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (requestCode == 99 && resultCode == RESULT_OK) { //返回污染源信息
            polluterE = (PolluterE) data.getSerializableExtra(Constants.INTENT_OBJ_KEY);
            setPolluterData();
        }
    }
}
